<?php
namespace Isas\Com\Indicator;

/**
 * Ma移动平均线
 * @author w.
 *
 */
class Ma extends AbstractIndicatorSupport {

    const KEY = 'ma';
	
	private $period;
	
	public function __construct($period,$model = null){
		$this->period = $period;
		$this->model = $model;
	}
	
	public function calc($bars){
		$firstBarIndex = $bars[0]['bar_index'];
		$calBarIndex = $firstBarIndex - $this->period - 1;
		if($calBarIndex<0)$calBarIndex = 0;
		// 补充前面周期的bar
		$supplyBars = $this->model->field('id,close,bar_index,'.$this->getKey())
			->order('bar_index asc')
			->where('bar_index >= '.$calBarIndex)
			->limit($this->period-1)->select();
		if($calBarIndex != 0){
			$bars = array_merge($supplyBars,$bars);	
		}	
		
	   	$sum = 0;
	  	$val = 0;
	 	$cnt = count($bars);
		for($i=$cnt-1;$i>=0;$i--){
			if($i>=($this->period-1)){
				$sum = 0;
	        	for($n=$i;$n>$i-$this->period;$n--){
	            	$sum += $bars[$n]['close'];
	        	}
	        	$val = round($sum/$this->period,2);
			} else {
				$val = 0;
			}
			$bars[$i][$this->getKey()] = $val;
		}
		//$bars = array_slice($bars,$this->period-1);
		
	   	return $bars;
	}
			
	public function save($bars){
		$cnt = count($bars);
		// 获取保存的键值
		$key = $this->getKey();
		$total = 0;
		for($i=0;$i<$cnt;$i++){
			if($i<$this->period && $bars[$i][$this->getKey()]==-1){
				$bars[$i][$this->getKey()] = 0;
			}
			echo $bars[$i][$this->getKey()].'</br>';
		    // 保存到数据库
		    $this->model->save($bars[$i]);	
		    $total++;
		}
		//info($this->getKey().':成功更新'.$total.'条');
		return $total;
	}

	private function getKey(){
	    return self::KEY.'_'.$this->period;
	}
}

?>
